package com.code.lightning.common;

import com.code.lightning.code.mysql.MySqlInfoAnalyse;
import com.code.lightning.code.oracle.OracleInfoAnalyse;
import com.code.lightning.common.api.BasicDataBaseInfoAnalyse;
import com.code.lightning.common.enums.LightingCore;
import com.code.lightning.common.exception.LightingGeneratorException;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;

/**
 * 数据库解析器
 * @author LGX_TvT
 * @date 2021-01-17 17:56
 */
@Slf4j
public class DataBaseInfoAnalyseFactory {

    private static DataBaseInfoAnalyseFactory dataBaseInfoAnalyse = new DataBaseInfoAnalyseFactory();

    private DataBaseInfoAnalyseFactory() {

    }

    /**
     * 初始化解析器
     * @return
     */
    public static DataBaseInfoAnalyseFactory getInstance() {
        return dataBaseInfoAnalyse;
    }

    /**
     * 根据数据库类型创建解析器
     * @param dbCategory 数据库类型 Mysql | Oracle
     * @return BasicDataBaseInfoAnalyse
     */
    public BasicDataBaseInfoAnalyse create(String dbCategory) {
        if (dbCategory == null) {
            log.error("create error, dbCategory is null");
            throw new RuntimeException("create error, dbCategory is null");
        }
        if (LightingCore.DataBaseCategory.MYSQL.getName().equalsIgnoreCase(dbCategory)) {
            return new MySqlInfoAnalyse();
        }
        log.error("create error, temporarily not available {}", dbCategory);
        throw new RuntimeException("create error, temporarily not available " + dbCategory);
    }

    /**
     * 根据数据库类型创建解析器
     * @param dbCategory 数据库类型 Mysql | Oracle
     * @param connection 数据库链接
     * @return BasicDataBaseInfoAnalyse
     */
    public BasicDataBaseInfoAnalyse create(String dbCategory, Connection connection) throws LightingGeneratorException {
        if (dbCategory == null) {
            log.error("create error, dbCategory is null");
            throw new RuntimeException("create error, dbCategory is null");
        }
        if (LightingCore.DataBaseCategory.MYSQL.getName().equalsIgnoreCase(dbCategory)) {
            log.info("create MySqlInfoAnalyse success...");
            return new MySqlInfoAnalyse(connection);
        }
        if (LightingCore.DataBaseCategory.ORACLE.getName().equalsIgnoreCase(dbCategory)) {
            log.info("create OracleInfoAnalyse success...");
            return new OracleInfoAnalyse(connection);
        }
        log.error("create error, temporarily not available {}", dbCategory);
        throw new LightingGeneratorException("create error, temporarily not available " + dbCategory);
    }

}
